package com.ruoyi.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.domain.Conlumn;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.service.IConlumnService;
import com.ruoyi.system.mapper.SysDeptMapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.domain.ColumnPermission;
import com.ruoyi.service.IColumnPermissionService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 栏目临时权限Controller
 * 
 * @author ruoyi
 * @date 2025-09-03
 */
@RestController
@RequestMapping("/conlumn/permission")
public class ColumnPermissionController extends BaseController
{
    @Autowired
    private IColumnPermissionService columnPermissionService;
    
    @Autowired
    private TokenService tokenService;
    
    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private IConlumnService conlumnService;

    /**
     * 查询栏目临时权限列表
     */
    //@PreAuthorize("@ss.hasPermi('conlumn:permission:list')")
    @GetMapping("/list")
    public TableDataInfo list(ColumnPermission columnPermission)
    {
        startPage();
        List<ColumnPermission> list = columnPermissionService.selectColumnPermissionList(columnPermission);
        return getDataTable(list);
    }

    /**
     * 导出栏目临时权限列表
     */
    //@PreAuthorize("@ss.hasPermi('conlumn:permission:export')")
    @Log(title = "栏目临时权限", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ColumnPermission columnPermission)
    {
        List<ColumnPermission> list = columnPermissionService.selectColumnPermissionList(columnPermission);
        ExcelUtil<ColumnPermission> util = new ExcelUtil<ColumnPermission>(ColumnPermission.class);
        util.exportExcel(response, list, "栏目临时权限数据");
    }

    /**
     * 获取栏目临时权限详细信息
     */
    //@PreAuthorize("@ss.hasPermi('conlumn:permission:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(columnPermissionService.selectColumnPermissionById(id));
    }

    /**
     * 新增栏目临时权限
     */
    //@PreAuthorize("@ss.hasPermi('conlumn:permission:add')")
    @Log(title = "栏目临时权限", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ColumnPermission columnPermission)
    {
        // 获取当前登录用户信息
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        columnPermission.setCreateBy(loginUser.getUser().getUserName());
        return toAjax(columnPermissionService.insertColumnPermission(columnPermission));
    }

    /**
     * 修改栏目临时权限
     */
    //@PreAuthorize("@ss.hasPermi('conlumn:permission:edit')")
    @Log(title = "栏目临时权限", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ColumnPermission columnPermission)
    {
        return toAjax(columnPermissionService.updateColumnPermission(columnPermission));
    }

    /**
     * 删除栏目临时权限
     */
    //@PreAuthorize("@ss.hasPermi('conlumn:permission:remove')")
    @Log(title = "栏目临时权限", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(columnPermissionService.deleteColumnPermissionByIds(ids));
    }
    
    /**
     * 根据栏目ID和部门ID查询权限
     */
//    @PreAuthorize("@ss.hasPermi('conlumn:permission:query')")
    @Anonymous
    @GetMapping("/check/{columnId}/{deptId}")
    public AjaxResult checkPermission(@PathVariable("columnId") Long columnId, @PathVariable("deptId") Long deptId)
    {
        ColumnPermission permission = columnPermissionService.selectColumnPermissionByColumnIdAndDeptId(columnId, deptId);
        return success(permission);
    }
    
    /**
     * 判断部门是否直接隶属于荆州市长江河道管理局（一级子部门）
     * @param dept 部门信息
     * @return 是否直接隶属于荆州市长江河道管理局
     */
    private boolean isDirectSubDeptOfJingZhou(SysDept dept) {
        // 如果部门本身就是"荆州市长江河道管理局"，则不认为是其下级部门
        if ("荆州市长江河道管理局".equals(dept.getDeptName())) {
            return false;
        }
        
        // 直接检查父部门是否为"荆州市长江河道管理局"
        // 如果父部门ID有效，直接查询父部门名称
        if (dept.getParentId() != null && dept.getParentId() > 0) {
            SysDept parentDept = sysDeptMapper.selectDeptById(dept.getParentId());
            if (parentDept != null && "荆州市长江河道管理局".equals(parentDept.getDeptName())) {
                return true;
            }
        }
        
        return false;
    }
    
    /**
     * 获取所有分局列表
     */
    //@PreAuthorize("@ss.hasPermi('conlumn:permission:list')")
    @GetMapping("/depts")
    public AjaxResult getDepts()
    {
        // 查询所有部门
        List<SysDept> depts = sysDeptMapper.selectDeptList(new SysDept());
        // 过滤出直接隶属于荆州市长江河道管理局的部门（分局），但排除市局/总局
        return success(depts.stream()
                .filter(this::isDirectSubDeptOfJingZhou)
                .filter(dept -> !"市局/总局".equals(dept.getDeptName()))
                .toArray());
    }
    
    /**
     * 检查分局是否拥有指定栏目的权限
     */
    @Anonymous
    @GetMapping("/checkPermission/{columnId}/{deptId}")
    public AjaxResult checkDeptColumnPermission(@PathVariable("columnId") Long columnId, @PathVariable("deptId") Long deptId) {
        // 查询栏目信息
        Conlumn conlumn = conlumnService.selectConlumnById(columnId);
        
        if (conlumn != null) {
            // 先检查当前部门是否有明确的权限设置
            ColumnPermission currentDeptPermission = columnPermissionService.selectColumnPermissionByColumnIdAndDeptId(columnId, deptId);
            
            // 如果当前部门有明确的权限设置
            if (currentDeptPermission != null) {
                // 检查权限类型，1-添加权限，2-移除权限
                if (currentDeptPermission.getPermissionType() != null && currentDeptPermission.getPermissionType() == 2) {
                    // 明确移除权限，直接返回false
                    return success(false);
                } else if (currentDeptPermission.getPermissionType() != null && currentDeptPermission.getPermissionType() == 1) {
                    // 明确添加权限，直接返回true
                    return success(true);
                }
            }
            
            // 如果是role为1的栏目（默认所有分局都有权限）
            if ("1".equals(conlumn.getRole())) {
                // 检查祖先部门是否有移除权限的记录
                boolean ancestorHasRemovedPermission = checkAncestorDeptRemovedPermission(columnId, deptId);
                if (ancestorHasRemovedPermission) {
                    // 祖先部门移除了权限，子部门也不应该有权限
                    return success(false);
                }
                
                // 检查祖先部门是否有明确添加权限的记录
                boolean ancestorHasAddedPermission = checkAncestorDeptAddedPermission(columnId, deptId);
                if (ancestorHasAddedPermission) {
                    // 祖先部门有添加权限，子部门也应该有权限
                    return success(true);
                }
                
                // 默认情况下role为1的栏目所有分局都有权限
                return success(true);
            } else {
                // 其他role的栏目，需要检查祖先部门是否有明确添加权限的记录
                boolean ancestorHasAddedPermission = checkAncestorDeptAddedPermission(columnId, deptId);
                return success(ancestorHasAddedPermission);
            }
        }
        
        return success(false);
    }
    
    /**
     * 检查祖先部门是否移除了指定栏目的权限
     * @param columnId 栏目ID
     * @param deptId 部门ID
     * @return 祖先部门是否移除了权限
     */
    private boolean checkAncestorDeptRemovedPermission(Long columnId, Long deptId) {
        // 获取部门信息
        SysDept dept = sysDeptMapper.selectDeptById(deptId);
        if (dept == null || dept.getAncestors() == null || dept.getAncestors().isEmpty()) {
            return false;
        }
        
        // 从 ancestors 中提取所有祖先部门ID
        String[] ancestorIds = dept.getAncestors().split(",");
        
        // 查询祖先部门中包含"分局"的部门是否移除了权限
        for (String ancestorId : ancestorIds) {
            if (!ancestorId.trim().isEmpty()) {
                try {
                    Long ancestorDeptId = Long.parseLong(ancestorId.trim());
                    SysDept ancestorDept = sysDeptMapper.selectDeptById(ancestorDeptId);
                    // 检查祖先部门是否包含"分局"
                    if (ancestorDept != null && ancestorDept.getDeptName() != null &&
                            ancestorDept.getDeptName().contains("分局")) {
                        // 检查祖先部门是否有该栏目权限记录
                        ColumnPermission permission = columnPermissionService.selectColumnPermissionByColumnIdAndDeptId(columnId, ancestorDeptId);
                        // 如果有移除权限的记录，返回true
                        if (permission != null && permission.getPermissionType() != null && permission.getPermissionType() == 2) {
                            return true;
                        }
                    }
                } catch (NumberFormatException e) {
                    // 忽略无效ID
                }
            }
        }
        return false;
    }
    
    /**
     * 检查祖先部门是否添加了指定栏目的权限
     * @param columnId 栏目ID
     * @param deptId 部门ID
     * @return 祖先部门是否添加了权限
     */
    private boolean checkAncestorDeptAddedPermission(Long columnId, Long deptId) {
        // 获取部门信息
        SysDept dept = sysDeptMapper.selectDeptById(deptId);
        if (dept == null || dept.getAncestors() == null || dept.getAncestors().isEmpty()) {
            return false;
        }
        
        // 从 ancestors 中提取所有祖先部门ID
        String[] ancestorIds = dept.getAncestors().split(",");
        
        // 查询祖先部门中包含"分局"的部门是否添加了权限
        for (String ancestorId : ancestorIds) {
            if (!ancestorId.trim().isEmpty()) {
                try {
                    Long ancestorDeptId = Long.parseLong(ancestorId.trim());
                    SysDept ancestorDept = sysDeptMapper.selectDeptById(ancestorDeptId);
                    // 检查祖先部门是否包含"分局"
                    if (ancestorDept != null && ancestorDept.getDeptName() != null &&
                            ancestorDept.getDeptName().contains("分局")) {
                        // 检查祖先部门是否有该栏目权限记录
                        ColumnPermission permission = columnPermissionService.selectColumnPermissionByColumnIdAndDeptId(columnId, ancestorDeptId);
                        // 如果有添加权限的记录，返回true
                        if (permission != null && permission.getPermissionType() != null && permission.getPermissionType() == 1) {
                            return true;
                        }
                    }
                } catch (NumberFormatException e) {
                    // 忽略无效ID
                }
            }
        }
        return false;
    }
    
}